package com.androidframelearn.event_rxjava;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button btn_run_scheduler;

    private TextView tv_test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 0.获取控件实例
        btn_run_scheduler = findViewById(R.id.btn_run_scheduler);
        tv_test = findViewById(R.id.tv_test);

        // 1.创建被观察者
        Observable observable = Observable.create(new ObservableOnSubscribe<String>() {
            // 2.实现回调方法subscribe()
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
                // 3.发送String类型的消息
                emitter.onNext("测试RxJava!");
                // 4.完成消息的发送
                emitter.onComplete();
            }
        });

        // 5.创建观察着
        Observer observer = new Observer<String>() {
            // 6.订阅后执行的方法
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            // 7.当被观察者执行onNext()的回调
            @Override
            public void onNext(@NonNull String s) {
                tv_test.setText(s);
                Log.i(TAG,"收到消息啦！");
            }

            // 8.当被观察者执行onError()的回调
            @Override
            public void onError(@NonNull Throwable e) {

            }

            // 9.当被观察者执行onComplete()的回调
            @Override
            public void onComplete() {
                Log.i(TAG,"消息接收已结束！");
            }
        };

        // 10.注册按钮点击事件
        btn_run_scheduler.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                observable.subscribe(observer);
            }
        });
    }
}